<html>
<head>
<title>JSON in JavaScript</title>
<style>
pre {font-family: "Courier New", Courier, mono; margin-left: 40pt}
</style>
</head>
<body bgcolor=linen>
<table width="100%" border="0">
  <tr>
    <td valign="middle" width=160 align="center"><a href="http://www.JSON.org"><img src="img/json160.gif" width="160" height="160" align=left border="0">
      </a>
    </td>
    <td valign="middle" align="center">
      <div style="background-color: white; margin-left: 40px; margin-right: 40px; border: 2px solid black; padding: 10px; font-family : serif;">
        <h1 align="center">JSON in JavaScript</h1>
      </div>
    </td>
  </tr>
</table>
<hr>
<p><a href="http://www.crockford.com/javascript">JavaScript</a> is a general 
  purpose programming language that was introduced as the page scripting 
  language for Netscape Navigator. <a href="http://www.crockford.com/javascript/javascript.html">It 
  is still widely believed to be a subset of Java, but it is not</a>. It 
  is a <a href="http://www.crockford.com/javascript/little.html">Scheme</a>-like 
  language with <a href="http://www.crockford.com/javascript/survey.html">C-like 
  syntax</a> and <a href="http://www.crockford.com/javascript/inheritance.html">soft 
  objects</a>. JavaScript was standardized in the <a href="http://www.ecma-international.org/publications/files/ecma-st/ECMA-262.pdf">ECMAScript 
  Language Specification, Third Edition</a>.</p>
<p><a href="http://www.JSON.org">JSON</a> is a subset of the object literal notation
  of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language
  with no muss or fuss.</p>
<pre>var myJSONObject = {&quot;bindings&quot;: [
        {&quot;ircEvent&quot;: &quot;PRIVMSG&quot;, &quot;method&quot;: &quot;newURI&quot;, &quot;regex&quot;: &quot;^http://.*&quot;},
        {&quot;ircEvent&quot;: &quot;PRIVMSG&quot;, &quot;method&quot;: &quot;deleteURI&quot;, &quot;regex&quot;: &quot;^delete.*&quot;},
        {&quot;ircEvent&quot;: &quot;PRIVMSG&quot;, &quot;method&quot;: &quot;randomURI&quot;, &quot;regex&quot;: &quot;^random.*&quot;}
    ]
};</pre>
<p>In this example, an object is created containing a single member <tt>&quot;bindings&quot;</tt>, which contains an array containing three objects, each containing <tt>&quot;ircEvent&quot;</tt>, <tt>&quot;method&quot;</tt>, and <tt>&quot;regex&quot;</tt> members.</p>
<p>Members can be retrieved using dot or subscript operators.</p>
<pre>myJSONObject.bindings[0].method    // &quot;newURI&quot;</pre>
<p>To convert a JSON text into an object, you can use the <tt>eval()</tt> 
  function. <tt>eval()</tt> invokes the JavaScript compiler. Since JSON 
  is a proper subset of JavaScript, the compiler will correctly parse the 
  text and produce an object structure. The text must be wrapped in parens 
  to avoid tripping on an ambiguity in JavaScript's syntax.</p>
<pre>var myObject = eval('(' + myJSONtext + ')');</pre>
<p> The <code>eval</code> function is very fast. However, it can compile 
  and execute any JavaScript program, so there can be security issues. The 
  use of <code>eval</code> is indicated when the source is trusted and competent. 
  It is much safer to use a JSON parser. In web applications over XMLHttpRequest, 
  communication is permitted only to the same origin that provide that page, 
  so it is trusted. But it might not be competent. If the server is not 
  rigorous in its JSON encoding, or if it does not scrupulously validate 
  all of its inputs, then it could deliver invalid JSON text that could 
  be carrying dangerous script. The <code>eval</code> function would execute 
  the script, unleashing its malice.</p>
<p>To defend against this, a JSON parser should be used. A JSON parser will 
  recognize only JSON text, rejecting all scripts. In browsers that provide 
  native JSON support, JSON parsers are also much faster than <code>eval</code>. 
  It is expected that native JSON support will be included in the next ECMAScript 
  standard. </p>
<pre>var myObject = JSON.parse(myJSONtext, reviver);</pre>
<p>The optional <code>reviver</code> parameter is a function that will be 
  called for every key and value at every level of the final result. Each 
  value will be replaced by the result of the <code>reviver</code> function. 
  This can be used to reform generic objects into instances of pseudoclasses, 
  or to transform date strings into <code>Date</code> objects.</p>
<pre>myData = JSON.parse(text, function (key, value) {
    var type;
    if (value && typeof value === 'object') {
        type = value.type;
        if (typeof type === 'string' && typeof window[type] === 'function') {
            return new (window[type])(value);
        }
    }
    return value;
});</pre>
<p>A JSON stringifier goes in the opposite direction, converting JavaScript
  data structures into JSON text. JSON does not support cyclic data structures,
  so be careful to not give cyclical structures to the JSON stringifier.</p>
<pre>var myJSONText = JSON.stringify(myObject, replacer);
</pre>
<p>If the <code>stringify</code> method sees an object that contains a <code>toJSON</code> 
  method, it calls that method, and stringifies the value returned. This 
  allows an object to determine its own JSON representation.</p>
<p>The <code>stringifier</code> method can take an optional array of strings.
  These strings are used to select the properties that will be included
  in the JSON text. </p>
<p>The <code>stringifier</code> method can take an optional replacer function. 
  It will be called after the <code>toJSON</code> method (if there is one) 
  on each of the values in the structure. It will be passed each key and 
  value as parameters, and <code>this</code> will be bound to object holding 
  the key. The value returned will be stringified. </p>
<p>Values that do not have a representation in JSON (such as functions and 
  <code>undefined</code>) are excluded.</p>
<p>Nonfinite numbers are replaced with <code>null</code>. To substitute 
  other values, you could use a replacer function like this:</p>
<pre>function replacer(key, value) {
    if (typeof value === 'number' &amp;&amp; !isFinite(value)) {
        return String(value);
    }
    return value;
}</pre>
<p>Giving a corresponding reviver to <code>JSON.parse</code> can undo that.</p>
<p> <a href="https://github.com/douglascrockford/JSON-js">The open source code of a JSON parser and JSON stringifier 
  is available.</a> When <a href="http://www.crockford.com/javascript/jsmin.html">minified</a> 
  it is less than 2.5K.</p>
</body>
</html>
